﻿using CodeApi.Context;
using CodeApi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CodeApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
 
    public class ArticlesController : ControllerBase
    {
        private readonly IndexContext _context;

        public ArticlesController(IndexContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 查询所有文章列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ArticleModel>>> Getarticles(int a = 5)
        {
            List<ArticleModel> articleModels = await _context.articles.ToListAsync();
            return articleModels.GetRange(articleModels.Count-a-1,a);
        }

        /// <summary>
        /// 需优化  根据文章类型查询
        /// </summary>
        /// <param name="Kind"></param>
        /// <returns></returns>
        // GET: api/Articles/5
        [HttpGet("{Kind}")]
        public async Task<ActionResult<IEnumerable<ArticleModel>>> GetArticleModel(int Kind)
        {
            List<ArticleModel> need = new List<ArticleModel>();
            IList list = await _context.articles.ToListAsync();
            foreach (ArticleModel item in list)
            {
                if (item.Kind == Kind)
                {
                    need.Add(item);
                }
            }
            return need;
        }

        // PUT: api/Articles/5  修改
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutArticleModel(int id, ArticleModel articleModel)
        {
            if (id != articleModel.ID)
            {
                return BadRequest();
            }

            _context.Entry(articleModel).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ArticleModelExists(id))
                {
                    return NotFound();
                }
                throw;
            }

            return NoContent();
        }


        /// <summary>
        /// 修改观看人数
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult<bool>> ChangeArticleViews(String path)
        {
            if (await this._context.articles.AnyAsync(t => t.Path == path))
            {
                int id = (this._context.articles.Where(t => t.Path == path).ToArray()[0] as ArticleModel).ID;
                var model = await _context.articles.FindAsync(id);
                _context.articles.Attach(model);
                model.Number++;
                await _context.SaveChangesAsync();
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 根据文章路径查询用户id
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpGet("path")]
        public async Task<ActionResult<int>> getUserId(String path)
        {
            if (await this._context.articles.AnyAsync(t => t.Path == path))
                return (this._context.articles.Where(t => t.Path == path).ToArray()[0] as ArticleModel).UID;
            else
                return 0;
        }

        [HttpGet]
        public async Task<IEnumerable<ArticleModel>> getUserArticle(int uid, int length)
        {
            if (this._context.articles.Any(t => t.UID == uid))
            {
                IList<ArticleModel> Need = new List<ArticleModel>();
                IList<ArticleModel> articles = await _context.articles.Where(t => t.UID == uid).ToListAsync();
                int len = articles.Count() > length ? length : articles.Count();
                for (int i = 0; i < len; i++)
                {
                    Need.Add(articles[i]);
                }
                return Need;
            }
            else
            {
                return null;
            }
        }

        // POST: api/Articles
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<ArticleModel>> PostArticleModel(ArticleModel articleModel, [FromForm] FilePostModel objFile)
        {
            _context.articles.Add(articleModel);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetArticleModel", new { id = articleModel.ID }, articleModel);
        }

        [HttpPost]
        public async Task<ActionResult> postFile([FromBody] FormFile formFile)
        {
            return new ObjectResult(new { code = 200 });
        }

        // DELETE: api/Articles/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteArticleModel(int id)
        {
            var articleModel = await _context.articles.FindAsync(id);
            if (articleModel == null)
            {
                return NotFound();
            }

            _context.articles.Remove(articleModel);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool ArticleModelExists(int id)
        {
            return _context.articles.Any(e => e.ID == id);
        }

        [HttpGet]
        public String getMarkDown()
        {
            return @"D:\WareHoues\code-c-core-web-api\CodeApi\CodeApi\Resource\markdown\test.md";
        }


        [HttpGet("{uid}")]
        public async Task<ActionResult> getUserViews(int uid)
        {
            int numbers = 0;
            if (_context.articles.Any(t=>t.UID==uid))
            {
                IQueryable<ArticleModel> articleModels = _context.articles.Where(t => t.UID == uid);
                foreach (var item in articleModels)
                {
                    numbers += item.Number;
                }
                return new ObjectResult(new { viewNumbers = numbers ,articleNumber = articleModels.Count()});
            }
            else
            {
                return new ObjectResult(new { viewNumbers = numbers }); ;
            }
        }
    }
}